<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">

  <script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.3">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.3" color="#222">





  <meta name="keywords" content="MongoDB,极简教程系列," />










<meta name="description" content="安装 MongoDB Windowns、Ubuntu17.10 下安装 MongoDB教程在此MongoDB 帮助要想获取命令列表，在 mongodb 客户端中输入 db.help()：1&amp;gt; db.help()   MongoDB 统计信息要想获取 MongoDB 服务器的统计信息，在 mongodb 客户端中输入 db.stat()：1&amp;gt; db.stats() 创建数据库use 命令">
<meta name="keywords" content="MongoDB,极简教程系列">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB 入门极简教程">
<meta property="og:url" content="http://www.kangvcar.com/MongoDB-入门极简教程/index.html">
<meta property="og:site_name" content="Kangvcar | Blogs">
<meta property="og:description" content="安装 MongoDB Windowns、Ubuntu17.10 下安装 MongoDB教程在此MongoDB 帮助要想获取命令列表，在 mongodb 客户端中输入 db.help()：1&amp;gt; db.help()   MongoDB 统计信息要想获取 MongoDB 服务器的统计信息，在 mongodb 客户端中输入 db.stat()：1&amp;gt; db.stats() 创建数据库use 命令">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2640591-631fbb680c6e70df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2640591-700a3972b10c5e25.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600">
<meta property="og:updated_time" content="2018-06-18T08:53:40.063Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB 入门极简教程">
<meta name="twitter:description" content="安装 MongoDB Windowns、Ubuntu17.10 下安装 MongoDB教程在此MongoDB 帮助要想获取命令列表，在 mongodb 客户端中输入 db.help()：1&amp;gt; db.help()   MongoDB 统计信息要想获取 MongoDB 服务器的统计信息，在 mongodb 客户端中输入 db.stat()：1&amp;gt; db.stats() 创建数据库use 命令">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/2640591-631fbb680c6e70df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.kangvcar.com/MongoDB-入门极简教程/"/>



  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "f8921861"
    });
  daovoice('update');
  </script>





  <title>MongoDB 入门极简教程 | Kangvcar | Blogs</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
      <a href="https://github.com/kangvcar/kangvcar.github.io" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#FD6C6C; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<!--       <a href="https://github.com/kangvcar/kangvcar.github.io"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
 -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Kangvcar | Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">知识的广度是深度的副产品</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.kangvcar.com/MongoDB-入门极简教程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kangvcar">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Kangvcar | Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB 入门极简教程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-15T04:15:52+08:00">
                2017-11-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MongoDB/" itemprop="url" rel="index">
                    <span itemprop="name">MongoDB</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/MongoDB-入门极简教程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="MongoDB-入门极简教程/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5,711
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  24
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="安装-MongoDB"><a href="#安装-MongoDB" class="headerlink" title="安装 MongoDB"></a>安装 MongoDB</h1><ul>
<li>Windowns、Ubuntu17.10 下<a href="http://www.jianshu.com/p/1c85bf051754" target="_blank" rel="external">安装 MongoDB教程在此</a><h2 id="MongoDB-帮助"><a href="#MongoDB-帮助" class="headerlink" title="MongoDB 帮助"></a>MongoDB 帮助</h2>要想获取命令列表，在 mongodb 客户端中输入 <code>db.help()</code>：<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash"> db.help()</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="MongoDB-统计信息"><a href="#MongoDB-统计信息" class="headerlink" title="MongoDB 统计信息"></a>MongoDB 统计信息</h2><p>要想获取 MongoDB 服务器的统计信息，在 mongodb 客户端中输入 <code>db.stat()</code>：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash"> db.stats()</span></span><br></pre></td></tr></table></figure></p>
<h1 id="创建数据库"><a href="#创建数据库" class="headerlink" title="创建数据库"></a>创建数据库</h1><h2 id="use-命令"><a href="#use-命令" class="headerlink" title="use 命令"></a>use 命令</h2><p>MongoDB 用 <code>use + 数据库名称</code> 的方式来创建数据库。 <code>use</code> 会创建一个新的数据库，如果该数据库存在，则返回这个数据库。</p>
<h3 id="语法格式"><a href="#语法格式" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>use</code> 语句的基本格式如下：<br><code>use DATABASE_NAME</code></p>
<h3 id="范例"><a href="#范例" class="headerlink" title="范例"></a>范例</h3><p>创建一个名为mydb的数据库，使用  <code>use</code> 语句如下：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">use mydb</span></span><br><span class="line">switched to db mydb</span><br><span class="line"><span class="meta">#</span><span class="bash"> 使用命令 db 检查当前选定的数据库。</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">db</span></span><br><span class="line">mydb</span><br></pre></td></tr></table></figure></p>
<p>使用命令 <code>show dbs</code> 来检查数据库列表。<br><figure class="highlight subunit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;show dbs</span><br><span class="line">local 0.78125GB</span><br><span class="line"><span class="keyword">test </span>0.23012GB</span><br></pre></td></tr></table></figure></p>
<p>刚创建的数据库（mydb）没有出现在列表中。为了让数据库显示出来，至少应该插入一个文档。<br><figure class="highlight subunit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.movie.insert(&#123;"name":"tutorials point"&#125;)</span><br><span class="line">&gt;show dbs</span><br><span class="line">local 0.78125GB</span><br><span class="line">mydb 0.23012GB</span><br><span class="line"><span class="keyword">test </span>0.23012GB</span><br></pre></td></tr></table></figure></p>
<p>在 MongoDB 中，默认的数据库是 test，如果你没有创建任何数据库，那么集合就会保存在 test 数据库中。</p>
<h1 id="删除数据库"><a href="#删除数据库" class="headerlink" title="删除数据库"></a>删除数据库</h1><h2 id="dropDatabase-方法"><a href="#dropDatabase-方法" class="headerlink" title="dropDatabase() 方法"></a>dropDatabase() 方法</h2><p>MongoDB 的 <code>dropDatabase()</code>命令用于删除已有数据库。</p>
<h3 id="语法格式-1"><a href="#语法格式-1" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>dropDatabase()</code> 命令的语法格式如下：<br><code>db.dropDatabase()</code><br>它将删除选定的数据库。如果没有选定要删除的数据库，则它会将默认的 test 数据库删除。</p>
<h3 id="范例-1"><a href="#范例-1" class="headerlink" title="范例"></a>范例</h3><p>首先使用 <code>show dbs</code> 来列出已有的数据库。<br><figure class="highlight subunit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;show dbs</span><br><span class="line">local 0.78125GB</span><br><span class="line">mydb 0.23012GB</span><br><span class="line"><span class="keyword">test </span>0.23012GB</span><br></pre></td></tr></table></figure></p>
<p>如果想删除新数据库 <mydb> ，如下面这样使用 <code>dropDatabase()</code>方法：<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;<span class="keyword">use</span> mydb</span><br><span class="line">switched to <span class="keyword">db</span> mydb</span><br><span class="line">&gt;<span class="keyword">db</span>.dropDatabase()</span><br><span class="line">&#123; <span class="string">"dropped"</span> : <span class="string">"mydb"</span>, <span class="string">"ok"</span> : 1 &#125;</span><br></pre></td></tr></table></figure></mydb></p>
<h1 id="创建集合"><a href="#创建集合" class="headerlink" title="创建集合"></a>创建集合</h1><h2 id="createCollection-方法"><a href="#createCollection-方法" class="headerlink" title="createCollection() 方法"></a>createCollection() 方法</h2><p>在 MongoDB 中，创建集合采用  <code>db.createCollection(name, options)</code>方法。</p>
<h3 id="语法格式-2"><a href="#语法格式-2" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>createCollection()</code> 方法的基本格式如下：<br><code>db.createCollection(name, options)</code><br>在该命令中， name 是所要创建的集合名称。 options 是一个用来指定集合配置的文档。</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>字符串</td>
<td>所要创建的集合名称</td>
</tr>
<tr>
<td>options</td>
<td>文档</td>
<td>可选。指定有关内存大小及索引的选项</td>
</tr>
</tbody>
</table>
<p>参数 options 是可选的，所以你必须指定的只有集合名称。下表列出了所有可用选项：</p>
<table>
<thead>
<tr>
<th>字段</th>
<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>capped</td>
<td>布尔</td>
<td>（可选）如果为 true，则创建固定集合。固定集合是指有着固定大小的集合，当达到最大值时，它会自动覆盖最早的文档。当该值为 true 时，必须指定 size 参数。</td>
</tr>
<tr>
<td>autoIndexID</td>
<td>布尔</td>
<td>（可选）如为 true，自动在 _id 字段创建索引。默认为 false。</td>
</tr>
<tr>
<td>size</td>
<td>数值</td>
<td>（可选）为固定集合指定一个最大值（以字节计）。如果 capped 为 true，也需要指定该字段。</td>
</tr>
<tr>
<td>max</td>
<td>数值</td>
<td>（可选）指定固定集合中包含文档的最大数量。在插入文档时，MongoDB 首先检查固定集合的 size 字段，然后检查 max 字段。</td>
</tr>
</tbody>
</table>
<h3 id="范例-2"><a href="#范例-2" class="headerlink" title="范例"></a>范例</h3><p>不带参数的 <code>createCollection()</code> 方法的基本格式为：<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;<span class="keyword">use</span> <span class="keyword">test</span></span><br><span class="line">switched to <span class="keyword">db</span> <span class="keyword">test</span></span><br><span class="line">&gt;<span class="keyword">db</span>.createCollection(<span class="string">"mycollection"</span>)</span><br><span class="line">&#123; <span class="string">"ok"</span> : 1 &#125;</span><br></pre></td></tr></table></figure></p>
<p>可以使用 <code>show collections</code> 来查看创建了的集合。<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">show collections</span></span><br><span class="line">mycollection</span><br><span class="line">system.indexes</span><br></pre></td></tr></table></figure></p>
<p>下面是带有几个关键参数的 <code>createCollection()</code>的用法：<br><figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.createCollection(<span class="string">"mycol"</span>, &#123; capped : <span class="type">true</span>, size : 6142800&#125; )</span><br><span class="line">&#123; <span class="string">"ok"</span> : 1 &#125;</span><br></pre></td></tr></table></figure></p>
<p>在 MongoDB 中，你不需要创建集合。当你插入一些文档时，MongoDB 会自动创建集合。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.tutorialspoint</span><span class="selector-class">.insert</span>(&#123;<span class="string">"name"</span> : <span class="string">"tutorialspoint"</span>&#125;)</span><br><span class="line">&gt;show collections</span><br><span class="line">mycol</span><br><span class="line">mycollection</span><br><span class="line">system.indexes</span><br><span class="line">tutorialspoint</span><br></pre></td></tr></table></figure></p>
<h1 id="删除集合"><a href="#删除集合" class="headerlink" title="删除集合"></a>删除集合</h1><h2 id="drop-方法"><a href="#drop-方法" class="headerlink" title="drop() 方法"></a>drop() 方法</h2><p>MongoDB 利用 <code>db.collection.drop()</code>来删除数据库中的集合。</p>
<p>###语法格式<br><code>drop()</code> 命令的基本格式如下：<br><code>db.COLLECTION_NAME.drop()</code></p>
<h3 id="范例-3"><a href="#范例-3" class="headerlink" title="范例"></a>范例</h3><p>首先检查在数据库 mydb 中已有集合：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">use mydb</span></span><br><span class="line">switched to db mydb</span><br><span class="line"><span class="meta">&gt;</span><span class="bash">show collections</span></span><br><span class="line">mycol</span><br><span class="line">mycollection</span><br><span class="line">system.indexes</span><br><span class="line">tutorialspoint</span><br></pre></td></tr></table></figure></p>
<p>接着删除集合 mycollection。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycollection</span><span class="selector-class">.drop</span>()</span><br><span class="line">true</span><br></pre></td></tr></table></figure></p>
<p>如果成功删除选定集合，则 <code>drop()</code>方法返回 true，否则返回false。</p>
<h1 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h1><p>MongoDB 支持如下数据类型：</p>
<ul>
<li>String：字符串。存储数据常用的数据类型。在 MongoDB 中，UTF-8 编码的字符串才是合法的。</li>
<li>Integer：整型数值。用于存储数值。根据你所采用的服务器，可分为 32 位或 64 位。</li>
<li>Boolean：布尔值。用于存储布尔值（真/假）。</li>
<li>Double：双精度浮点值。用于存储浮点值。</li>
<li>Min/Max keys：将一个值与 BSON（二进制的 JSON）元素的最低值和最高值相对比。</li>
<li>Arrays：用于将数组或列表或多个值存储为一个键。</li>
<li>Timestamp：时间戳。记录文档修改或添加的具体时间。</li>
<li>Object：用于内嵌文档。</li>
<li>Null：用于创建空值。</li>
<li>Symbol：符号。该数据类型基本上等同于字符串类型，但不同的是，它一般用于采用特殊符号类型的语言。</li>
<li>Date：日期时间。用 UNIX 时间格式来存储当前日期或时间。你可以指定自己的日期时间：创建 Date 对<br>象，传入年月日信息。</li>
<li>Object ID：对象 ID。用于创建文档的 ID。</li>
<li>Binary Data：二进制数据。用于存储二进制数据。</li>
<li>Code：代码类型。用于在文档中存储 JavaScript 代码。</li>
<li>Regular expression：正则表达式类型。用于存储正则表达式。</li>
</ul>
<h1 id="插入文档"><a href="#插入文档" class="headerlink" title="插入文档"></a>插入文档</h1><h2 id="insert-方法"><a href="#insert-方法" class="headerlink" title="insert() 方法"></a>insert() 方法</h2><p>要想将数据插入 MongoDB 集合中，需要使用<code>insert()</code>或 <code>save()</code>方法。<br><code>insert()</code>或 <code>save()</code>方法d的区别是当主键重复时，<code>insert()</code>会报错， <code>save()</code>会覆盖原有内容。</p>
<h3 id="语法格式-3"><a href="#语法格式-3" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>insert()</code>方法的基本格式为：<br><code>db.COLLECTION_NAME.insert(document)</code></p>
<h3 id="范例-1"><a href="#范例-1" class="headerlink" title="范例 1"></a>范例 1</h3><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; 传入一条数据 格式：<span class="selector-tag">db</span><span class="selector-class">.mycol</span><span class="selector-class">.insert</span>(&#123;&#125;)</span><br><span class="line">&gt;<span class="selector-tag">db</span><span class="selector-class">.mycol</span><span class="selector-class">.insert</span>(&#123;</span><br><span class="line"><span class="attribute">title</span>: <span class="string">'MongoDB Overview'</span>,</span><br><span class="line">description: <span class="string">'MongoDB is no sql database'</span>,</span><br><span class="line">by: <span class="string">'tutorials point'</span>,</span><br><span class="line">url: <span class="string">'http://www.tutorialspoint.com'</span>,</span><br><span class="line">tags: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line">likes: <span class="number">100</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>mycol 是上一节所创建的集合的名称。如果数据库中不存在该集合，那么 MongoDB 会创建该集合，并向其中插入文档。<br>在插入的文档中，如果我们没有指定 _id 参数，那么 MongoDB 会自动为文档指定一个唯一的 ID。<br>为了，你可以将用 insert() 方法传入一个文档数组，范例如下：</p>
<h3 id="范例-2"><a href="#范例-2" class="headerlink" title="范例 2"></a>范例 2</h3><figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&gt; 传入多条数据 格式：<span class="selector-tag">db</span><span class="selector-class">.mycol</span><span class="selector-class">.insert</span>([&#123;&#125;,&#123;&#125;,&#123;&#125;])</span><br><span class="line">&gt;<span class="selector-tag">db</span><span class="selector-class">.post</span><span class="selector-class">.insert</span>([</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">title</span>: <span class="string">'MongoDB Overview'</span>,</span><br><span class="line"><span class="attribute">description</span>: <span class="string">'MongoDB is no sql database'</span>,</span><br><span class="line"><span class="attribute">by</span>: <span class="string">'tutorials point'</span>,</span><br><span class="line"><span class="attribute">url</span>: <span class="string">'http://www.tutorialspoint.com'</span>,</span><br><span class="line"><span class="attribute">tags</span>: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line"><span class="attribute">likes</span>: <span class="number">100</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">title</span>: <span class="string">'NoSQL Database'</span>,</span><br><span class="line"><span class="attribute">description</span>: <span class="string">'NoSQL database doesn'</span>t have tables',</span><br><span class="line"><span class="attribute">by</span>: <span class="string">'tutorials point'</span>,</span><br><span class="line"><span class="attribute">url</span>: <span class="string">'http://www.tutorialspoint.com'</span>,</span><br><span class="line"><span class="attribute">tags</span>: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line"><span class="attribute">likes</span>: <span class="number">20</span>,</span><br><span class="line"><span class="attribute">comments</span>: [</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">user</span>:<span class="string">'user1'</span>,</span><br><span class="line"><span class="attribute">message</span>: <span class="string">'My first comment'</span>,</span><br><span class="line"><span class="attribute">dateCreated</span>: new Date(<span class="number">2013</span>,<span class="number">11</span>,<span class="number">10</span>,<span class="number">2</span>,<span class="number">35</span>),</span><br><span class="line"><span class="attribute">like</span>: <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line">]</span><br><span class="line">&#125;</span><br><span class="line">])</span><br></pre></td></tr></table></figure>
<p>也可以用 <code>db.post.save(document)</code>插入文档。如果没有指定文档的 _id ，那么<code>save()</code> 就和 <code>insert()</code>完全一样了。如果指定了文档的 _id ，那么它会覆盖掉含有 save() 方法中指定的 _id 的文档的全部数据。</p>
<h1 id="查询文档"><a href="#查询文档" class="headerlink" title="查询文档"></a>查询文档</h1><h2 id="find-方法"><a href="#find-方法" class="headerlink" title="find() 方法"></a>find() 方法</h2><p>要想查询 MongoDB 集合中的数据，使用 <code>find()</code> 方法。</p>
<p>###语法格式<br><code>find()</code> 方法的基本格式为：<br><code>db.COLLECTION_NAME.find()</code><br><code>find()</code>方法会以非结构化的方式来显示所有文档。<br><code>pretty()</code> 方法用格式化方式显示结果，使用的是 <code>pretty()</code> 方法。<br>语法格式<br><code>&gt;db.COLLECTION_NAME.find().pretty()</code></p>
<h2 id="范例-4"><a href="#范例-4" class="headerlink" title="范例"></a>范例</h2><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>().pretty()</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span>: ObjectId(<span class="number">7</span>df78ad8902c),</span><br><span class="line"><span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>,</span><br><span class="line"><span class="string">"description"</span>: <span class="string">"MongoDB is no sql database"</span>,</span><br><span class="line"><span class="string">"by"</span>: <span class="string">"tutorials point"</span>,</span><br><span class="line"><span class="string">"url"</span>: <span class="string">"http://www.tutorialspoint.com"</span>,</span><br><span class="line"><span class="string">"tags"</span>: [<span class="string">"mongodb"</span>, <span class="string">"database"</span>, <span class="string">"NoSQL"</span>],</span><br><span class="line"><span class="string">"likes"</span>: <span class="string">"100"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>除了 find() 方法之外，还有一个 findOne() 方法，它只返回一个文档。</p>
<h2 id="MongoDB-中类似于-WHERE-子句的语句"><a href="#MongoDB-中类似于-WHERE-子句的语句" class="headerlink" title="MongoDB 中类似于 WHERE 子句的语句"></a>MongoDB 中类似于 WHERE 子句的语句</h2><p>如果想要基于一些条件来查询文档，可以使用下列操作。</p>
<table>
<thead>
<tr>
<th>操作</th>
<th>格式</th>
<th>范例</th>
<th>RDBMS中的类似语句</th>
</tr>
</thead>
<tbody>
<tr>
<td>等于</td>
<td>{<key>:<value> }</value></key></td>
<td>db.mycol.find({“by”:”tutorials point”}).pretty()</td>
<td>where by = ‘tutorials point’</td>
</tr>
<tr>
<td>小于</td>
<td>{<key>:{$lt:<value>}}</value></key></td>
<td>db.mycol.find({“likes”:{$lt:50}}).pretty()</td>
<td>where likes &lt; 50</td>
</tr>
<tr>
<td>小于或等于</td>
<td>{<key>:{$lte:<value>}}</value></key></td>
<td>db.mycol.find({“likes”:{$lte:50}}).pretty()</td>
<td>where likes &lt;= 50</td>
</tr>
<tr>
<td>大于</td>
<td>{<key>:{$gt:<value>}}</value></key></td>
<td>db.mycol.find({“likes”:{$gt:50}}).pretty()</td>
<td>where likes &gt; 50</td>
</tr>
<tr>
<td>大于或等于</td>
<td>{<key>:{$gte:<value>}}</value></key></td>
<td>db.mycol.find({“likes”:{$gte:50}}).pretty()</td>
<td>where likes &gt;= 50</td>
</tr>
<tr>
<td>不等于</td>
<td>{<key>:{$ne:<value>}}</value></key></td>
<td>db.mycol.find({“likes”:{$ne:50}}).pretty()</td>
<td>where likes != 50</td>
</tr>
</tbody>
</table>
<h2 id="MongoDB-中的-And-条件"><a href="#MongoDB-中的-And-条件" class="headerlink" title="MongoDB 中的 And 条件"></a>MongoDB 中的 And 条件</h2><h3 id="语法格式-4"><a href="#语法格式-4" class="headerlink" title="语法格式"></a>语法格式</h3><p>在 <code>find()</code> 方法中，如果传入多个键，并用逗号( , )分隔它们，那么 MongoDB 会把它看成是 AND 条件。AND条件的基本语法格式为：<br><code>db.mycol.find({key1:value1, key2:value2}).pretty()</code></p>
<h3 id="范例-5"><a href="#范例-5" class="headerlink" title="范例"></a>范例</h3><p>下例将展示所有由 “tutorials point” 发表的标题为 “MongoDB Overview” 的教程。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>(&#123;<span class="string">"by"</span>:<span class="string">"tutorials point"</span>,<span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>&#125;).pretty()</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span>: ObjectId(<span class="number">7</span>df78ad8902c),</span><br><span class="line"><span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>,</span><br><span class="line"><span class="string">"description"</span>: <span class="string">"MongoDB is no sql database"</span>,</span><br><span class="line"><span class="string">"by"</span>: <span class="string">"tutorials point"</span>,</span><br><span class="line"><span class="string">"url"</span>: <span class="string">"http://www.tutorialspoint.com"</span>,</span><br><span class="line"><span class="string">"tags"</span>: [<span class="string">"mongodb"</span>, <span class="string">"database"</span>, <span class="string">"NoSQL"</span>],</span><br><span class="line"><span class="string">"likes"</span>: <span class="string">"100"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于上例这种情况，RDBMS 采用的 WHERE 子句将会是： <code>where by=&#39;tutorials point&#39; AND title=&#39;MongoDB
Overview&#39;</code>。你可以在 find 子句中传入任意的键值对。</p>
<h2 id="MongoDB-中的-OR-条件"><a href="#MongoDB-中的-OR-条件" class="headerlink" title="MongoDB 中的 OR 条件"></a>MongoDB 中的 OR 条件</h2><h3 id="语法格式-5"><a href="#语法格式-5" class="headerlink" title="语法格式"></a>语法格式</h3><p>若基于 OR 条件来查询文档，可以使用关键字<code>$or</code>。 OR 条件的基本语法格式为：<br><figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;<span class="selector-tag">db</span><span class="selector-class">.mycol</span><span class="selector-class">.find</span>(</span><br><span class="line">&#123;</span><br><span class="line">$<span class="attribute">or</span>: [</span><br><span class="line">&#123;<span class="attribute">key1</span>: value1&#125;, &#123;<span class="attribute">key2</span>:value2&#125;</span><br><span class="line">]</span><br><span class="line">&#125;</span><br><span class="line">)<span class="selector-class">.pretty</span>()</span><br></pre></td></tr></table></figure></p>
<p>###范例<br>下例将展示所有由 “tutorials point” 发表的标题为 “MongoDB Overview” 的教程。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt; 格式：db.mycol.find(&#123;$or:[&#123;&#125;,&#123;&#125;]&#125;)</span><br><span class="line">&gt;db.mycol.find(&#123;$or:[&#123;<span class="string">"by"</span>:<span class="string">"tutorials point"</span>&#125;,&#123;<span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>&#125;]&#125;).pretty()</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span>: ObjectId(<span class="number">7</span>df78ad8902c),</span><br><span class="line"><span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>,</span><br><span class="line"><span class="string">"description"</span>: <span class="string">"MongoDB is no sql database"</span>,</span><br><span class="line"><span class="string">"by"</span>: <span class="string">"tutorials point"</span>,</span><br><span class="line"><span class="string">"url"</span>: <span class="string">"http://www.tutorialspoint.com"</span>,</span><br><span class="line"><span class="string">"tags"</span>: [<span class="string">"mongodb"</span>, <span class="string">"database"</span>, <span class="string">"NoSQL"</span>],</span><br><span class="line"><span class="string">"likes"</span>: <span class="string">"100"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="结合使用-AND-与-OR-条件"><a href="#结合使用-AND-与-OR-条件" class="headerlink" title="结合使用 AND 与 OR 条件"></a>结合使用 AND 与 OR 条件</h2><h3 id="范例-6"><a href="#范例-6" class="headerlink" title="范例"></a>范例</h3><p>下例所展示文档的条件为：喜欢数大于 100，标题是 “MongoDB Overview”，或者是由 “tutorials point”所发表的。响应的 SQL WHERE 子句为： <code>where likes&gt;10 AND (by = &#39;tutorials point&#39; OR title = &#39;MongoDB Overview&#39;)</code><br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt; 格式：db.mycol.find(&#123;&#125;,$or:[&#123;&#125;,&#123;&#125;])</span><br><span class="line">&gt;db.mycol.find(&#123;<span class="string">"likes"</span>: &#123;$gt:<span class="number">10</span>&#125;, $or: [&#123;<span class="string">"by"</span>: <span class="string">"tutorials point"</span>&#125;,&#123;<span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>&#125;]&#125;).pretty()</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span>: ObjectId(<span class="number">7</span>df78ad8902c),</span><br><span class="line"><span class="string">"title"</span>: <span class="string">"MongoDB Overview"</span>,</span><br><span class="line"><span class="string">"description"</span>: <span class="string">"MongoDB is no sql database"</span>,</span><br><span class="line"><span class="string">"by"</span>: <span class="string">"tutorials point"</span>,</span><br><span class="line"><span class="string">"url"</span>: <span class="string">"http://www.tutorialspoint.com"</span>,</span><br><span class="line"><span class="string">"tags"</span>: [<span class="string">"mongodb"</span>, <span class="string">"database"</span>, <span class="string">"NoSQL"</span>],</span><br><span class="line"><span class="string">"likes"</span>: <span class="string">"100"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="更新文档"><a href="#更新文档" class="headerlink" title="更新文档"></a>更新文档</h1><p>MongoDB 中的 update() 与 save() 方法都能用于更新集合中的文档。 update() 方法更新已有文档中的值，而 save() 方法则是用传入该方法的文档来替换已有文档。</p>
<h2 id="update-方法"><a href="#update-方法" class="headerlink" title="update()方法"></a>update()方法</h2><p><code>update()</code> 方法更新已有文档中的值。</p>
<h3 id="语法格式-6"><a href="#语法格式-6" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>update()</code>方法基本格式如下：<br><code>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)</code></p>
<h3 id="范例-7"><a href="#范例-7" class="headerlink" title="范例"></a>范例</h3><p>假如 mycol 集合中有下列数据：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="attr">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="attr">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="attr">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>下面的例子将把文档原标题 ‘MongoDB Overview’ 替换为新的标题 ‘New MongoDB Tutorial’。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.mycol.<span class="keyword">update</span>(&#123;<span class="string">'title'</span>:<span class="string">'MongoDB Overview'</span>&#125;,&#123;$set:&#123;<span class="string">'title'</span>:<span class="string">'New MongoDB Tutorial'</span>&#125;&#125;)</span><br><span class="line">&gt;db.mycol.find()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="string">"title"</span>:<span class="string">"New MongoDB Tutorial"</span>&#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="string">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>MongoDB 默认只更新单个文档，要想更新多个文档，需要把参数 multi 设为 true 。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.mycol.<span class="keyword">update</span>(&#123;<span class="string">'title'</span>:<span class="string">'MongoDB Overview'</span>&#125;,&#123;$set:&#123;<span class="string">'title'</span>:<span class="string">'New MongoDB Tutorial'</span>&#125;&#125;,&#123;multi:true&#125;)</span><br></pre></td></tr></table></figure></p>
<h2 id="save-方法"><a href="#save-方法" class="headerlink" title="save() 方法"></a>save() 方法</h2><p><code>save()</code>方法利用传入该方法的文档来替换已有文档。<br>语法格式<br><code>save()</code> 方法基本语法格式如下：<br><code>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})</code></p>
<p>###范例<br>下例更新 _id 为 ‘5983548781331adf45ec7’ 的文档。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.save</span>(</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="string">"title"</span>:<span class="string">"Tutorials Point New Topic"</span>, <span class="string">"by"</span>:<span class="string">"Tutorials Point"</span></span><br><span class="line">&#125;</span><br><span class="line">)</span><br><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="string">"title"</span>:<span class="string">"New MongoDB Tutorial"</span>&#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="string">"title"</span>:<span class="string">"Tutorials Point New Topic"</span>, <span class="string">"by"</span>:<span class="string">"Tutorials Point"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="删除文档"><a href="#删除文档" class="headerlink" title="删除文档"></a>删除文档</h1><h2 id="remove-方法"><a href="#remove-方法" class="headerlink" title="remove() 方法"></a>remove() 方法</h2><p>MongoDB 利用 <code>remove()</code> 方法 清除集合中的文档。它有 2 个可选参数：</p>
<ul>
<li>deletion criteria：（可选）删除文档的标准。</li>
<li>justOne：（可选）如果设为 true 或 1，则只删除一个文档。<h3 id="语法格式-7"><a href="#语法格式-7" class="headerlink" title="语法格式"></a>语法格式</h3><code>remove()</code>方法的基本语法格式如下所示：<br><code>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)</code><h3 id="范例-8"><a href="#范例-8" class="headerlink" title="范例"></a>范例</h3>假如 mycol 集合中包含下列数据：<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="attr">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="attr">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="attr">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>下面我们将删除其中所有标题为 ‘MongoDB Overview’ 的文档。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.remove</span>(&#123;<span class="string">'title'</span>:<span class="string">'MongoDB Overview'</span>&#125;)</span><br><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="string">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="只删除一个文档"><a href="#只删除一个文档" class="headerlink" title="只删除一个文档"></a>只删除一个文档</h2><p>如果有多个记录，而你只想删除第一条记录，那么就设置 remove() 方法中的 justOne 参数：<br><code>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)</code></p>
<h2 id="删除所有文档"><a href="#删除所有文档" class="headerlink" title="删除所有文档"></a>删除所有文档</h2><p>如果没有指定删除标准，则 MongoDB 会将集合中所有文档都予以删除。 这等同于 SQL 中的 truncate 命令。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.remove</span>()</span><br><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>()</span><br></pre></td></tr></table></figure></p>
<h1 id="映射"><a href="#映射" class="headerlink" title="映射"></a>映射</h1><p>在 MongoDB 中，映射（Projection）指的是只选择文档中的必要数据，而非全部数据。如果文档有 5 个字段，而你只需要显示 3 个，则只需选择 3 个字段即可。</p>
<h2 id="find-方法-1"><a href="#find-方法-1" class="headerlink" title="find()方法"></a>find()方法</h2><p>MongoDB 的查询文档曾介绍过<code>find()</code> 方法，不管是利用 AND 或 OR 条件来获取想要的字段列表都是显示一个文档的所有字段。要想限制，可以利用 0 或 1 来设置字段列表。1 用于显示字段，0 用于隐藏字段。</p>
<h3 id="语法格式-8"><a href="#语法格式-8" class="headerlink" title="语法格式"></a>语法格式</h3><p>带有映射的 find() 方法的基本语法格式为：<br><code>db.COLLECTION_NAME.find({},{KEY:1})</code></p>
<h3 id="范例-9"><a href="#范例-9" class="headerlink" title="范例"></a>范例</h3><p>假如 mycol 集合拥有下列数据：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="attr">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="attr">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="attr">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>下例将在查询文档时显示文档标题。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.mycol.find(&#123;&#125;,&#123;<span class="string">"title"</span>:<span class="number">1</span>,<span class="string">"_id"</span>:<span class="number">0</span>&#125;)</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意：在执行 find() 方法时， _id 字段是一直显示的。如果不想显示该字段，则可以将其设为 0。</p>
<h1 id="限制记录"><a href="#限制记录" class="headerlink" title="限制记录"></a>限制记录</h1><h2 id="limit-方法"><a href="#limit-方法" class="headerlink" title="limit() 方法"></a>limit() 方法</h2><p>要想限制 MongoDB 中的记录，可以使用 <code>limit()</code>方法。<code>limit()</code> 方法接受一个数值类型的参数，其值为想要显示的文档数。</p>
<h3 id="语法格式-9"><a href="#语法格式-9" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>limit()</code>方法的基本语法格式为：<br><code>db.COLLECTION_NAME.find().limit(NUMBER)</code></p>
<h3 id="范例-10"><a href="#范例-10" class="headerlink" title="范例"></a>范例</h3><p>假设 mycol 集合拥有下列数据：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="attr">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="attr">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="attr">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>下例将在查询文档时只显示 2 个文档。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.mycol.find(&#123;&#125;,&#123;<span class="string">"title"</span>:<span class="number">1</span>,_id:<span class="number">0</span>&#125;).limit(<span class="number">2</span>)</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果未指定<code>limit()</code> 方法中的数值参数，则将显示该集合内的所有文档。</p>
<h2 id="skip-方法"><a href="#skip-方法" class="headerlink" title="skip() 方法"></a>skip() 方法</h2><h3 id="语法格式-10"><a href="#语法格式-10" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>skip()</code>方法基本语法格式为：<br><code>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)</code></p>
<h3 id="范例-11"><a href="#范例-11" class="headerlink" title="范例"></a>范例</h3><p>下例将只显示第二个文档：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="string">"title"</span>:<span class="number">1</span>,_id:<span class="number">0</span>&#125;).limit(<span class="number">1</span>).skip(<span class="number">1</span>)</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意： <code>skip()</code> 方法中的默认值为 0。</p>
<h1 id="记录排序"><a href="#记录排序" class="headerlink" title="记录排序"></a>记录排序</h1><h2 id="sort-方法"><a href="#sort-方法" class="headerlink" title="sort() 方法"></a>sort() 方法</h2><p>MongoDB 中的文档排序是通过 <code>sort()</code>方法来实现的。 <code>sort()</code> 方法可以通过一些参数来指定要进行排序的字段，并使用 1 和 -1 来指定排序方式，其中 1 表示升序，而 -1 表示降序。</p>
<h3 id="语法格式-11"><a href="#语法格式-11" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>sort()</code> 方法基本格式为：<br><code>db.COLLECTION_NAME.find().sort({KEY:1})</code></p>
<h3 id="范例-12"><a href="#范例-12" class="headerlink" title="范例"></a>范例</h3><p>假设集合 myycol 包含下列数据：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec5), <span class="attr">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec6), <span class="attr">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123; <span class="attr">"_id"</span> : ObjectId(<span class="number">5983548781331</span>adf45ec7), <span class="attr">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>下面的范例将显示按照降序排列标题的文档。<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.mycol.find(&#123;&#125;,&#123;<span class="string">"title"</span>:<span class="number">1</span>,_id:<span class="number">0</span>&#125;).sort(&#123;<span class="string">"title"</span>:-<span class="number">1</span>&#125;)</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"Tutorials Point Overview"</span>&#125;</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"NoSQL Overview"</span>&#125;</span><br><span class="line">&#123;<span class="string">"title"</span>:<span class="string">"MongoDB Overview"</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意，如果不指定排序规则， sort() 方法将按照升序排列显示文档。</p>
<h1 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h1><p>索引能够实现高效地查询。没有索引，MongoDB 就必须扫描集合中的所有文档，才能找到匹配查询语句的文档。这种扫描毫无效率可言，需要处理大量的数据。<br>索引是一种特殊的数据结构，将一小块数据集保存为容易遍历的形式。索引能够存储某种特殊字段或字段集的值，并按照索引指定的方式将字段值进行排序。</p>
<h2 id="ensureIndex-方法"><a href="#ensureIndex-方法" class="headerlink" title="ensureIndex() 方法"></a>ensureIndex() 方法</h2><p>要想创建索引，需要使用 MongoDB 的 ensureIndex() 方法。</p>
<h3 id="语法格式-12"><a href="#语法格式-12" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>ensureIndex()</code>方法的基本语法格式为：<br><code>db.COLLECTION_NAME.ensureIndex({KEY:1})</code><br>这里的 key 是想创建索引的字段名称，1 代表按升序排列字段值。-1 代表按降序排列。</p>
<h3 id="范例-13"><a href="#范例-13" class="headerlink" title="范例"></a>范例</h3><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.ensureIndex</span>(&#123;<span class="string">"title"</span>:<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>可以为 <code>ensureIndex()</code> 方法传入多个字段，从而为多个字段创建索引。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db<span class="selector-class">.mycol</span><span class="selector-class">.ensureIndex</span>(&#123;<span class="string">"title"</span>:<span class="number">1</span>,<span class="string">"description"</span>:-<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<p><code>ensureIndex()</code> 方法也可以接受一些可选参数，如下所示：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>background</td>
<td>布尔值</td>
<td>在后台构建索引，从而不干扰数据库的其他活动。取值为 true 时，代表在后台构建索引。默认值为 false</td>
</tr>
<tr>
<td>unique</td>
<td>布尔值</td>
<td>创建一个唯一的索引，从而当索引键匹配了索引中一个已存在值时，集合不接受文档的插入。取值为 true 代表创建唯一性索引。默认值为 false 。</td>
</tr>
<tr>
<td>name</td>
<td>字符串</td>
<td>索引名称。如果未指定，MongoDB 会结合索引字段名称和排序序号，生成一个索引名称。</td>
</tr>
<tr>
<td>dropDups</td>
<td>布尔值</td>
<td>在可能有重复的字段内创建唯一性索引。ongoDB 只在某个键第一次出现时进行索引，去除该键后续出现时的所有文档。</td>
</tr>
<tr>
<td>sparse</td>
<td>布尔值</td>
<td>如果为 true，索引只引用带有指定字段的文档。这些索引占据的空间较小，但在一些情况下的表现也不同（特别是排序）。默认值为 false 。</td>
</tr>
<tr>
<td>expireAfterSeconds</td>
<td>整型值</td>
<td>指定一个秒数值，作为 TTL 来控制 MongoDB 保持集合中文档的时间。</td>
</tr>
<tr>
<td>v</td>
<td>索引版本</td>
<td>索引版本号。默认的索引版本跟创建索引时运行的 MongoDB 版本号有关。</td>
</tr>
<tr>
<td>weights</td>
<td>文档</td>
<td>数值，范围从 1 到 99, 999。表示就字段相对于其他索引字段的重要性。</td>
</tr>
<tr>
<td>default_language</td>
<td>字符串</td>
<td>对文本索引而言，用于确定停止词列表，以及词干分析器（stemmer）与断词器（tokenizer）的规则。默认值为 english。</td>
</tr>
<tr>
<td>language_override</td>
<td>字符串</td>
<td>对文本索引而言，指定了文档所包含的字段名，该语言将覆盖默认语言。默认值为 language。</td>
</tr>
</tbody>
</table>
<h1 id="聚合"><a href="#聚合" class="headerlink" title="聚合"></a>聚合</h1><p>聚合操作能够处理数据记录并返回计算结果。聚合操作能将多个文档中的值组合起来，对成组数据执行各种操作，返回单一的结果。它相当于 SQL 中的 count(*) 组合 group by。</p>
<h2 id="aggregate-方法"><a href="#aggregate-方法" class="headerlink" title="aggregate() 方法"></a>aggregate() 方法</h2><p>对于 MongoDB 中的聚合操作，应该使用 <code>aggregate()</code>方法。</p>
<h3 id="语法格式-13"><a href="#语法格式-13" class="headerlink" title="语法格式"></a>语法格式</h3><p><code>aggregate()</code> 方法中的基本格式如下所示：<br><code>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)</code></p>
<h3 id="范例-14"><a href="#范例-14" class="headerlink" title="范例"></a>范例</h3><p>假如某个集合包含下列数据：<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line"><span class="attribute">_id</span>: <span class="built_in">ObjectId</span>(7df78ad8902c)</span><br><span class="line">title: <span class="string">'MongoDB Overview'</span>,</span><br><span class="line">description: <span class="string">'MongoDB is no sql database'</span>,</span><br><span class="line">by_user: <span class="string">'tutorials point'</span>,</span><br><span class="line">url: <span class="string">'http://www.tutorialspoint.com'</span>,</span><br><span class="line">tags: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line">likes: <span class="number">100</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">_id</span>: <span class="built_in">ObjectId</span>(7df78ad8902d)</span><br><span class="line">title: <span class="string">'NoSQL Overview'</span>,</span><br><span class="line">description: <span class="string">'No sql database is very fast'</span>,</span><br><span class="line">by_user: <span class="string">'tutorials point'</span>,</span><br><span class="line">url: <span class="string">'http://www.tutorialspoint.com'</span>,</span><br><span class="line">tags: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line">likes: <span class="number">10</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">_id</span>: <span class="built_in">ObjectId</span>(7df78ad8902e)</span><br><span class="line">title: <span class="string">'Neo4j Overview'</span>,</span><br><span class="line">description: <span class="string">'Neo4j is no sql database'</span>,</span><br><span class="line">by_user: <span class="string">'Neo4j'</span>,</span><br><span class="line">url: <span class="string">'http://www.neo4j.com'</span>,</span><br><span class="line">tags: [<span class="string">'neo4j'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line">likes: <span class="number">750</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>假如想从上述集合中，归纳出一个列表，以显示每个用户写的教程数量，需要像下面这样使用 aggregate() 方法：<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.mycol.aggregate([&#123;$group : &#123;_id : <span class="string">"$by_user"</span>, num_tutorial : &#123;$sum : <span class="number">1</span>&#125;&#125;&#125;])</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"result"</span> : [</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span> : <span class="string">"tutorials point"</span>,</span><br><span class="line"><span class="string">"num_tutorial"</span> : <span class="number">2</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">"_id"</span> : <span class="string">"Neo4j"</span>,</span><br><span class="line"><span class="string">"num_tutorial"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">],</span><br><span class="line"><span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>假如用 SQL 来处理上述查询，则需要使用这样的命令：<code>select by_user, count(*) from mycol group by by_user</code>。<br>上例使用 <strong>by_user</strong> 字段来组合文档，每遇到一次 <code>by_user</code>，就递增之前的合计值。下面是聚合表达式列表。</p>
<table>
<thead>
<tr>
<th>表达式</th>
<th>描述</th>
<th>范例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$sum</code></td>
<td>对集合中所有文档的定义值进行加和操作</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, num_tutorial : {$sum : &quot;$likes&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$avg</code></td>
<td>对集合中所有文档的定义值进行平均值</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, num_tutorial : {$avg : &quot;$likes&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$min</code></td>
<td>计算集合中所有文档的对应值中的最小值</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, num_tutorial : {$min : &quot;$likes&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$max</code></td>
<td>计算集合中所有文档的对应值中的最大值</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, num_tutorial : {$max : &quot;$likes&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$push</code></td>
<td>将值插入到一个结果文档的数组中</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, url : {$push: &quot;$url&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$addToSet</code></td>
<td>将值插入到一个结果文档的数组中，但不进行复制</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, url : {$addToSet : &quot;$url&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$first</code></td>
<td>根据成组方式，从源文档中获取第一个文档。但只有对之前应用过 <code>$sort</code> 管道操作符的结果才有意义。</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, first_url : {$first : &quot;$url&quot;}}}])</code></td>
</tr>
<tr>
<td><code>$last</code></td>
<td>根据成组方式，从源文档中获取最后一个文档。但只有对之前进行过 <code>$sort</code> 管道操作符的结果才有意义。</td>
<td><code>db.mycol.aggregate([{$group : {_id : &quot;$by_user&quot;, last_url : {$last : &quot;$url&quot;}}}])</code></td>
</tr>
</tbody>
</table>
<h3 id="管道的概念"><a href="#管道的概念" class="headerlink" title="管道的概念"></a>管道的概念</h3><p>在 UNIX 命令 Shell 中，管道（pipeline）概念指的是能够在一些输入上执行一个操作，然后将输出结果用作下一个命令的输入。MongoDB 的聚合架构也支持这种概念。管道中有很多阶段（stage），在每一阶段中，管道操作符都会将一组文档作为输入，产生一个结果文档（或者管道终点所得到的最终 JSON 格式的文档），然后再将其用在下一阶段。<br>聚合架构中可能采取的管道操作符有：</p>
<ul>
<li><strong>$project</strong> 用来选取集合中一些特定字段。</li>
<li><strong>$match</strong> 过滤操作。减少用作下一阶段输入的文档的数量。</li>
<li><strong>$group</strong> 如上所述，执行真正的聚合操作。</li>
<li><strong>$sort</strong> 对文档进行排序。</li>
<li><strong>$skip</strong> 在一组文档中，跳过指定数量的文档。</li>
<li><strong>$limit</strong> 将查看文档的数目限制为从当前位置处开始的指定数目。</li>
<li><strong>$unwind</strong> 解开使用数组的文档。当使用数组时，数据处于预连接状态，通过该操作，数据重新回归为各个单独的文档的状态。利用该阶段性操作可增加下一阶段性操作的文档数量。</li>
</ul>
<h1 id="创建备份"><a href="#创建备份" class="headerlink" title="创建备份"></a>创建备份</h1><h2 id="数据库备份"><a href="#数据库备份" class="headerlink" title="数据库备份"></a>数据库备份</h2><p>为了在 MongoDB 中创建数据库备份，需要使用 <strong>mongodump</strong> 命令。该命令会将服务器上的所有数据都转储到 dump 目录中。你可以使用很多选项来限制转储的数据量，或者创建远程服务器备份。</p>
<h3 id="语法格式-14"><a href="#语法格式-14" class="headerlink" title="语法格式"></a>语法格式</h3><p><strong>mongodump</strong> 命令的基本语法格式为：<br><code>mongodump</code></p>
<h3 id="范例-15"><a href="#范例-15" class="headerlink" title="范例"></a>范例</h3><p>开启 mongod 服务器。假设 mongod 服务器运行在 localhost 上，端口为 27017。在命令行上输入命令，在 MongoDB 实例的 bin 目录下输入 <strong>mongodump</strong> 命令。<br>假设 mycol 集合包含如下数据：<br><code>&gt;mongodump</code><br>上述命令会连接在 127.0.0.1 运行的服务器（端口为 27017），将所有数据备份到 <strong>/bin/dump</strong> 上。命令输出结果如下图所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2640591-631fbb680c6e70df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600" alt="创建备份"></p>
<p>mongodump 命令其实包含很多选项。</p>
<table>
<thead>
<tr>
<th>语法格式</th>
<th>描述</th>
<th>范例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>mongodump --host HOST_NAME --port PORT_NUMBER</code></td>
<td>该命令将指定 mongod 实例上的所有数据库都进行了备份</td>
<td><code>mongodump --host tutorialspoint.com --port 27017</code></td>
</tr>
<tr>
<td><code>mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY</code></td>
<td>该命令将指定数据库内容存放目录和备份输出目录</td>
<td><code>mongodump --dbpath /data/db/ --out /data/backup/</code></td>
</tr>
<tr>
<td><code>mongodump --collection COLLECTION --db DB_NAME</code></td>
<td>该命令只备份那些指定路径上的指定数据库</td>
<td><code>mongodump --collection mycol --db test</code></td>
</tr>
</tbody>
</table>
<h1 id="恢复备份"><a href="#恢复备份" class="headerlink" title="恢复备份"></a>恢复备份</h1><h2 id="重新恢复数据"><a href="#重新恢复数据" class="headerlink" title="重新恢复数据"></a>重新恢复数据</h2><p>恢复备份数据使用 <strong>mongorestore</strong> 命令，该命令将备份目录中的所有数据给予恢复。</p>
<h3 id="语法格式-15"><a href="#语法格式-15" class="headerlink" title="语法格式"></a>语法格式</h3><p><strong>mongorestore</strong> 命令的基本语法格式为：<br><code>&gt; mongorestore</code></p>
<h3 id="范例-16"><a href="#范例-16" class="headerlink" title="范例"></a>范例</h3><p>该命令输入结果如下图所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2640591-700a3972b10c5e25.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600" alt="恢复备份"></p>

      
    </div>
    
    
    


  


    

    
      <div>
        <div align="center">
 
   <div class="">
   <p>&nbsp</p>
   <p>&nbsp</p>
   <p><span>
   <b>本文地址：</b><a href="/MongoDB-入门极简教程/" title="MongoDB 入门极简教程">http://www.kangvcar.com/MongoDB-入门极简教程/</a><br/><b>转载请注明出处，谢谢！</b>
   </span></p>
   </div>
 
</div>


<div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，随意打赏！您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Kangvcar 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Kangvcar 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------感谢您的阅读-------------</div>
    
</div>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"><i class="fa fa-tag"></i> MongoDB</a>
          
            <a href="/tags/极简教程系列/" rel="tag"><i class="fa fa-tag"></i> 极简教程系列</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/CentOS配置本地Yum源、阿里云Yum源、163Yum源、并配置Yum源的优先级/" rel="next" title="CentOS配置本地Yum源、阿里云Yum源、163Yum源、并配置Yum源的优先级">
                <i class="fa fa-chevron-left"></i> CentOS配置本地Yum源、阿里云Yum源、163Yum源、并配置Yum源的优先级
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Python操作MongoDB-极简教程/" rel="prev" title="Python操作MongoDB - 极简教程">
                Python操作MongoDB - 极简教程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMTgzNi84NDAw"></div>


  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/uploads/avatar.png"
                alt="Kangvcar" />
            
              <p class="site-author-name" itemprop="name">Kangvcar</p>
              <p class="site-description motion-element" itemprop="description">知识的广度是深度的副产品</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">32</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/kangvcar" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://cv.kangvcar.com" target="_blank" title="我的简历">
                    
                      <i class="fa fa-fw fa-user"></i>我的简历</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://twitter.com/kangvcar" target="_blank" title="Twitter">
                    
                      <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/d9c480744afd" target="_blank" title="简书">
                    
                      <i class="fa fa-fw fa-globe"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://blog.csdn.net/kangvcar" target="_blank" title="CSDN">
                    
                      <i class="fa fa-fw fa-globe"></i>CSDN</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://my.oschina.net/kangvcar/blog" target="_blank" title="OSChina">
                    
                      <i class="fa fa-fw fa-globe"></i>OSChina</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:kangvcar@126.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#安装-MongoDB"><span class="nav-number">1.</span> <span class="nav-text">安装 MongoDB</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-帮助"><span class="nav-number">1.1.</span> <span class="nav-text">MongoDB 帮助</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-统计信息"><span class="nav-number">1.2.</span> <span class="nav-text">MongoDB 统计信息</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建数据库"><span class="nav-number">2.</span> <span class="nav-text">创建数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#use-命令"><span class="nav-number">2.1.</span> <span class="nav-text">use 命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式"><span class="nav-number">2.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例"><span class="nav-number">2.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除数据库"><span class="nav-number">3.</span> <span class="nav-text">删除数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#dropDatabase-方法"><span class="nav-number">3.1.</span> <span class="nav-text">dropDatabase() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-1"><span class="nav-number">3.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-1"><span class="nav-number">3.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建集合"><span class="nav-number">4.</span> <span class="nav-text">创建集合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#createCollection-方法"><span class="nav-number">4.1.</span> <span class="nav-text">createCollection() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-2"><span class="nav-number">4.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-2"><span class="nav-number">4.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除集合"><span class="nav-number">5.</span> <span class="nav-text">删除集合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#drop-方法"><span class="nav-number">5.1.</span> <span class="nav-text">drop() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-3"><span class="nav-number">5.1.1.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据类型"><span class="nav-number">6.</span> <span class="nav-text">数据类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#插入文档"><span class="nav-number">7.</span> <span class="nav-text">插入文档</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#insert-方法"><span class="nav-number">7.1.</span> <span class="nav-text">insert() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-3"><span class="nav-number">7.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-1"><span class="nav-number">7.1.2.</span> <span class="nav-text">范例 1</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-2"><span class="nav-number">7.1.3.</span> <span class="nav-text">范例 2</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询文档"><span class="nav-number">8.</span> <span class="nav-text">查询文档</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#find-方法"><span class="nav-number">8.1.</span> <span class="nav-text">find() 方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#范例-4"><span class="nav-number">8.2.</span> <span class="nav-text">范例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-中类似于-WHERE-子句的语句"><span class="nav-number">8.3.</span> <span class="nav-text">MongoDB 中类似于 WHERE 子句的语句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-中的-And-条件"><span class="nav-number">8.4.</span> <span class="nav-text">MongoDB 中的 And 条件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-4"><span class="nav-number">8.4.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-5"><span class="nav-number">8.4.2.</span> <span class="nav-text">范例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-中的-OR-条件"><span class="nav-number">8.5.</span> <span class="nav-text">MongoDB 中的 OR 条件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-5"><span class="nav-number">8.5.1.</span> <span class="nav-text">语法格式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结合使用-AND-与-OR-条件"><span class="nav-number">8.6.</span> <span class="nav-text">结合使用 AND 与 OR 条件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-6"><span class="nav-number">8.6.1.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#更新文档"><span class="nav-number">9.</span> <span class="nav-text">更新文档</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#update-方法"><span class="nav-number">9.1.</span> <span class="nav-text">update()方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-6"><span class="nav-number">9.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-7"><span class="nav-number">9.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#save-方法"><span class="nav-number">9.2.</span> <span class="nav-text">save() 方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除文档"><span class="nav-number">10.</span> <span class="nav-text">删除文档</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#remove-方法"><span class="nav-number">10.1.</span> <span class="nav-text">remove() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-7"><span class="nav-number">10.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-8"><span class="nav-number">10.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#只删除一个文档"><span class="nav-number">10.2.</span> <span class="nav-text">只删除一个文档</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除所有文档"><span class="nav-number">10.3.</span> <span class="nav-text">删除所有文档</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#映射"><span class="nav-number">11.</span> <span class="nav-text">映射</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#find-方法-1"><span class="nav-number">11.1.</span> <span class="nav-text">find()方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-8"><span class="nav-number">11.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-9"><span class="nav-number">11.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#限制记录"><span class="nav-number">12.</span> <span class="nav-text">限制记录</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#limit-方法"><span class="nav-number">12.1.</span> <span class="nav-text">limit() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-9"><span class="nav-number">12.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-10"><span class="nav-number">12.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#skip-方法"><span class="nav-number">12.2.</span> <span class="nav-text">skip() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-10"><span class="nav-number">12.2.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-11"><span class="nav-number">12.2.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#记录排序"><span class="nav-number">13.</span> <span class="nav-text">记录排序</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#sort-方法"><span class="nav-number">13.1.</span> <span class="nav-text">sort() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-11"><span class="nav-number">13.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-12"><span class="nav-number">13.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#索引"><span class="nav-number">14.</span> <span class="nav-text">索引</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ensureIndex-方法"><span class="nav-number">14.1.</span> <span class="nav-text">ensureIndex() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-12"><span class="nav-number">14.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-13"><span class="nav-number">14.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#聚合"><span class="nav-number">15.</span> <span class="nav-text">聚合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#aggregate-方法"><span class="nav-number">15.1.</span> <span class="nav-text">aggregate() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-13"><span class="nav-number">15.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-14"><span class="nav-number">15.1.2.</span> <span class="nav-text">范例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管道的概念"><span class="nav-number">15.1.3.</span> <span class="nav-text">管道的概念</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建备份"><span class="nav-number">16.</span> <span class="nav-text">创建备份</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库备份"><span class="nav-number">16.1.</span> <span class="nav-text">数据库备份</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-14"><span class="nav-number">16.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-15"><span class="nav-number">16.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#恢复备份"><span class="nav-number">17.</span> <span class="nav-text">恢复备份</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#重新恢复数据"><span class="nav-number">17.1.</span> <span class="nav-text">重新恢复数据</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法格式-15"><span class="nav-number">17.1.1.</span> <span class="nav-text">语法格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范例-16"><span class="nav-number">17.1.2.</span> <span class="nav-text">范例</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kangvcar</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv">
    本站访客数:<span id="busuanzi_value_site_pv"></span>次
</span>
</div>








  <span class="post-meta-divider">|</span>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共32.7k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://kangvcar.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://www.kangvcar.com/MongoDB-入门极简教程/';
          this.page.identifier = 'MongoDB-入门极简教程/';
          this.page.title = 'MongoDB 入门极简教程';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://kangvcar.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  












<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  



  
    <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  
  
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
